package com.kyle.silverbullet.admin.controller;

import com.kyle.silverbullet.admin.api.SercurityFeignService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import static org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction.clientRegistrationId;

@RestController
@Slf4j
@RequestMapping("/admin")
public class TestEndPointController {
    @Autowired
    private WebClient webClient;
    @Value("${messages.base-uri}")
    private String messagesBaseUri;

    @Autowired
    private SercurityFeignService sercurityFeignService;

    @GetMapping("/api/HelloWorld")
    public String apiHelloWorld() {
        return sercurityFeignService.apiHelloWorld();
    }

    @GetMapping(value = "/api/HelloWorld2")
    public String apiHelloWorld2() {
        return retrieveMessages("messaging-client-client-creds");
    }

    @GetMapping("/api/HelloWorld3")
    public Mono<String> index(@AuthenticationPrincipal Mono<OAuth2User> oauth2User) {
        return oauth2User
                .map(OAuth2User::getName)
                .map(name -> String.format("Hi, %s", name));
    }

    @GetMapping("/api/HelloWorld4")
    public Mono<String> HelloWorld4() {
        return retrieveMessagesA("messaging-client-client-creds");
    }

    private Mono<String> retrieveMessagesA(String clientRegistrationId) {
        return this.webClient
                .get()
                .uri(this.messagesBaseUri)
                .attributes(clientRegistrationId(clientRegistrationId))
                .retrieve()
                .bodyToMono(String.class)
                ;
    }


    private String retrieveMessages(String clientRegistrationId) {
        return this.webClient
                .get()
                .uri(this.messagesBaseUri)
                .attributes(clientRegistrationId(clientRegistrationId))
                .retrieve()
                .bodyToMono(String.class)
                .block();
    }


    @GetMapping("/")
    public String index(@AuthenticationPrincipal Jwt jwt) {
        return String.format("Hello, %s!", jwt.getSubject());
    }
}